import React, {FC, useEffect, useMemo, useRef, useState} from "react";
import {useDebounceFn, useRequest, useSetState, useTitle} from "ahooks";
import { Empty, Spin, Typography } from "antd";
import { useSearchParams } from "react-router-dom";
import styles from "./Common.module.scss";
import QuesCard from "../../components/QuesCard";
import SearchList from "../../components/Search";
import { getQuestionListService } from "../../services/question";
import { LIST_SEARCH_KEY } from "../../constant";
import styStar from "./Loading.module.scss"
//标星问卷的加载方式：
//使用和list不同的加载方式，下拉框的加载方式。
//这里要进行防抖操作。也就是频繁触发但只触发一次的操作。
//这里就不需要用useQuestionSearch，也就是说不用去

const Star: FC = () => {
  useTitle("妖妖问卷 - 标星问卷");
  const { Title } = Typography;

  const [list, setList] = useState([]);
  const [isstar, setIsstar] = useState(false);

  const [total, setTotal] = useState(0);

  const [page, setPage] = useState(1);

  const [searchPrams] = useSearchParams();

  const haveMoreData = total > list.length || false;

  const contianerRef = useRef<HTMLDivElement>(null);

  const keyword= searchPrams.get(LIST_SEARCH_KEY) || "";
  //实现当在其他页的情况下，点击搜索页可以重置进行重新搜索
    useEffect(()=>{
        setPage(1);
        setIsstar(false);
        setTotal(0);
        setList([]);
    },[keyword])





  const { run: tryLoadMore } = useDebounceFn(
    () => {
      const elem = contianerRef.current;
      if (elem === null) {
        return;
      }
      const domRef = elem.getBoundingClientRect();
      if (domRef === null) {
        return;
      }
      const { bottom } = domRef;

      if (bottom <= document.body.clientHeight) {
        load();
          setIsstar(true);
      }
    },
    { wait: 1000 },
  );
  //1.当页面加载的时候，或者url参数变化的时候，重新触发加载

  const { run: load, loading } = useRequest(
    async () => {
      const data = await getQuestionListService({
        page,
        pageSize: 10,
        keyword
      });
      return data;
    },
    {
      manual: true,
      onSuccess(result) {
        const { list: lis = [], total = 0 } = result;
        setList(list.concat(lis));
        setTotal(total);
        setPage(page + 1);
      },
    },
  );

  useEffect(() => {
    tryLoadMore();
  }, [searchPrams]);

  //2.当页面滚动的时候触发加载
  //不过得等到loading加载出来再进行刷新

  useEffect(() => {
    if (haveMoreData) {
      window.addEventListener("scroll", tryLoadMore);
    }
    return () => {
      window.removeEventListener("scroll", tryLoadMore);
    };
  }, [haveMoreData, searchPrams]);

  //使用useMom优化
  const LoadMore = useMemo(
      () => {
          if (!isstar ||loading) {
              return <Spin />;
          }
          if (total === 0) {
              return <Empty>暂无数据</Empty>;
          }
          if (!haveMoreData) {
              return <span>没有更多数据。。。</span>;
          }
          return<div className={styStar.myElement}>
              加载更多...
          </div>
      },[isstar,loading,haveMoreData]
  )

  return (
    <div>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={4}>标星问卷</Title>
        </div>
        <div className={styles.right}>
          <SearchList></SearchList>
        </div>
      </div>
      <div className={styles.content}>
        {/*<div style={{height:"2000px"}}></div>*/}
        {/*{loading && (*/}
        {/*  <div style={{ textAlign: "center" }}>*/}
        {/*    <Spin />*/}
        {/*  </div>*/}
        {/*)}*/}
        {/*{!loading && list.length === 0 && <Empty description={"暂无数据"} />}*/}
        {list.length > 0 &&
          list
            //todo 这里的拦截应该是后端数据处理后的，也就是业务逻辑不应该是给前端来写
            // .filter((tem:any) => tem.isStar)
            .map((tem: any) => {
              const { _id } = tem;
              return (
                //进行父子组件的传递
                //子组件中定义参数
                <QuesCard key={_id} {...tem}></QuesCard>
              );
            })}
      </div>
      <div className={styles.footer}>
        <div ref={contianerRef}>
            {LoadMore}
        </div>
      </div>
    </div>
  );
};
export default Star;
